import { QueryByGeometryParameters, SpatialQueryMode, QueryService, LayerInfoService, FilterParameter } from '@supermap/iclient-ol'
import Point from 'ol/geom/Point'

export const getMapLayers = (map) => {
  const layers = map.getLayers().getArray()
  return layers
}

export const getLayerInfo = (layer) => {
  const source = layer.getSource()
  if (source.options.url) {
    const layerSevice = new LayerInfoService(source.options.url)
    return layerSevice.getLayersInfo()
  }
}

/**
 * 点选查询
 * @param {*} layer
 * @param {*} coordinate
 * @returns
 */
export const queryFeature = async (layer, coordinate) => {
  const { url } = layer.getProperties()
  if (!url) return
  const layerinfo = await getLayerInfo(layer)
  const { result } = layerinfo
  const promiseAll = []
  // 遍历图层
  result.subLayers.layers.forEach(async (item) => {
    if (item.visible) {
      const { caption } = item
      const queryParam = new QueryByGeometryParameters({
        queryParams: new FilterParameter({
          name: caption
        }),
        prjCoordSys: { epsgCode: 4326 },
        geometry: new Point(coordinate),
        returnContent: true,
        startRecord: 0,
        returnFeatureWithFieldCaption: true
      }, SpatialQueryMode.INTERSECT)
      // 发送查询请求
      const queryService = new QueryService(url)
      promiseAll.push(queryService.queryByGeometry(queryParam))
    }
  })
  return Promise.all(promiseAll.map(promise => promise.catch(error => error)))
}

export const queryLegend = async (layer) => {
  const { url } = layer.getProperties()
  if (!url) return
  const layerinfo = await getLayerInfo(layer)
  const { result } = layerinfo
  const legend = []

  result.subLayers.layers.forEach(async (item) => {
    if (item.visible && item.theme && item.theme.items) {
      const items = item.theme.items.filter(theme => theme.visible)
      items.forEach(legenditem => {
        legend.push(legenditem)
      })
    }
  })
  return legend
}
